<template>
  <div class="hot-articles-page">
    <div class="page-header">
      <h4>宣教信息 - 热门文章</h4>
      <button class="add-btn" @click="handleAdd">增加</button>
    </div>

    <table class="data-table">
      <thead>
      <tr>
        <th>序号</th>
        <th>名称</th>
        <th>描述</th>
        <th>链接</th>
        <th>图片</th>
        <th>管理</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(item, index) in filteredList" :key="item.id">
        <td>{{ index + 1 }}</td>
        <td>{{ item.name }}</td>
        <td>{{ item.description }}</td>
        <td class="link-cell">{{ item.pcurl }}</td>
        <td><img :src="item.picture" class="article-img" alt="文章图片"></td>
        <!-- 管理列按钮布局优化，与其他页面保持一致 -->
        <td class="action-cell">
          <button
              :class="['status-btn', item.isused === '启用' ? 'success' : 'danger']"
              @click="handleStatusChange(item)"
          >
            {{ item.isused }}
          </button>
          <button
              class="edit-btn primary"
              @click="handleEdit(item)"
          >
            修改
          </button>
        </td>
      </tr>
      <tr v-if="filteredList.length === 0">
        <td colspan="6" class="empty-tip">暂无数据</td>
      </tr>
      </tbody>
    </table>

    <!-- 增加/编辑对话框 -->
    <div class="dialog-mask" v-if="showDialog">
      <div class="dialog-container">
        <div class="dialog-header">
          <h5>{{ isEdit ? '修改热门文章' : '增加热门文章' }}</h5>
          <button class="close-btn" @click="showDialog = false">×</button>
        </div>
        <div class="dialog-content">
          <div class="form-item">
            <label>名称：</label>
            <input
                type="text"
                v-model="formData.name"
                :maxlength="10"
                placeholder="请输入名称（最多10字）"
            >
            <span class="char-count">{{ formData.name.length }}/10</span>
          </div>

          <div class="form-item">
            <label>描述：</label>
            <textarea
                v-model="formData.description"
                :maxlength="20"
                placeholder="请输入描述（最多20字）"
            ></textarea>
            <span class="char-count">{{ formData.description.length }}/20</span>
          </div>

          <div class="form-item">
            <label>链接：</label>
            <input
                type="text"
                v-model="formData.pcurl"
                :maxlength="100"
                placeholder="请输入链接（最多100字）"
            >
            <span class="char-count">{{ formData.pcurl.length }}/100</span>
          </div>

          <div class="image-upload-area">
            <div class="image-preview" v-if="imageUrl">
              <img :src="imageUrl" class="preview-img" alt="预览图">
            </div>
            <div class="image-placeholder" v-else>
              图片预览区域
            </div>
            <button class="upload-btn" @click="triggerFileSelect">点击上传图片</button>
            <input
                type="file"
                ref="fileInput"
                accept="image/*"
                @change="handleFileChange"
                style="display: none;"
            >
          </div>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="showDialog = false">取消</button>
          <button class="submit-btn" @click="handleSubmit">提交</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 脚本部分逻辑不变，保持原有功能
import { apiClient } from '@/api/apiClient'

export default {
  name: 'XuanjiaoHotArticles',
  data() {
    return {
      articlesList: [],
      filteredList: [],
      showDialog: false,
      isEdit: false,
      currentItem: null,
      imageUrl: '',
      tempImageFile: null, // 存储临时的图片文件对象
      MAX_IMAGE_SIZE: 20 * 1024 * 1024, // 20MB
      formData: {
        name: '',
        description: '',
        pcurl: ''
      }
    }
  },
  created() {
    this.fetchArticlesData()
  },
  methods: {
    // 获取热门文章数据
    async fetchArticlesData() {
      try {
        const res = await apiClient.get('/patient/getAllHotArticles')

        if (res.data.code === 1) {
          this.articlesList = res.data.data || []
          this.filterDataByAuthority()
        } else {
          this.showToast('获取热门文章数据失败', 'error')
        }
      } catch (error) {
        console.error('获取热门文章数据出错:', error)
        this.showToast('获取数据失败，请重试', 'error')
      }
    },

    // 根据权限过滤数据
    filterDataByAuthority() {
      const userAuthority = localStorage.getItem('authority') || ''
      this.filteredList = this.articlesList.filter(
          item => item.authority === userAuthority
      )
    },

    // 计算启用的数量
    getEnabledCount() {
      return this.filteredList.filter(item => item.isused === '启用').length
    },

    // 处理增加按钮点击
    handleAdd() {
      if (this.getEnabledCount() >= 6) {
        this.showToast('启用数量太多请进行筛选', 'warning')
        return
      }

      this.isEdit = false
      this.currentItem = null
      this.imageUrl = ''
      this.tempImageFile = null
      this.formData = {
        name: '',
        description: '',
        pcurl: ''
      }
      this.showDialog = true
    },

    // 处理编辑按钮点击
    handleEdit(item) {
      this.isEdit = true
      this.currentItem = { ...item }
      this.imageUrl = item.picture
      this.tempImageFile = null
      this.formData = {
        name: item.name,
        description: item.description,
        pcurl: item.pcurl
      }
      this.showDialog = true
    },

    // 处理状态切换
    async handleStatusChange(item) {
      const newStatus = item.isused === '启用' ? '禁用' : '启用'

      // 如果是从禁用变为启用，检查数量是否超过6
      if (newStatus === '启用' && this.getEnabledCount() >= 6) {
        this.showToast('启用数量太多请进行筛选', 'warning')
        return
      }

      try {
        const res = await apiClient.post(
            '/patient/changeHotArticlesIsused',
            {
              id: item.id,
              isused: newStatus
            }
        )

        if (res.data.code === 1) {
          this.showToast(`已${newStatus}`, 'success')
          this.fetchArticlesData()
        } else {
          this.showToast(`操作失败: ${res.data.msg || ''}`, 'error')
        }
      } catch (error) {
        console.error('修改状态出错:', error)
        this.showToast('操作失败，请重试', 'error')
      }
    },

    // 触发文件选择
    triggerFileSelect() {
      this.$refs.fileInput.click()
    },

    // 处理文件选择
    handleFileChange(e) {
      const file = e.target.files[0]
      if (!file) return

      // 验证文件大小
      if (file.size > this.MAX_IMAGE_SIZE) {
        this.showToast('图片大小不能超过20MB', 'error')
        this.clearFileInput()
        return
      }

      // 显示预览
      this.tempImageFile = file
      const reader = new FileReader()
      reader.onload = (event) => {
        this.imageUrl = event.target.result
      }
      reader.readAsDataURL(file)

      // 清空input值，以便可以重复选择同一文件
      this.clearFileInput()
    },

    // 清空文件输入框
    clearFileInput() {
      if (this.$refs.fileInput) {
        this.$refs.fileInput.value = ''
      }
    },

    // 上传图片
    async uploadImage() {
      if (!this.tempImageFile) return null

      const formData = new FormData()
      formData.append('file', this.tempImageFile)

      try {
        const res = await apiClient.post('/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })

        if (res.data.code === 1) {
          return res.data.data // 返回图片URL
        } else {
          throw new Error(res.data.msg || '上传失败')
        }
      } catch (error) {
        console.error('上传图片错误:', error)
        this.showToast(error.message || '上传失败，请重试', 'error')
        return null
      }
    },

    // 处理提交
    async handleSubmit() {
      // 验证表单
      if (!this.formData.name.trim()) {
        this.showToast('请输入名称', 'warning')
        return
      }

      if (!this.formData.description.trim()) {
        this.showToast('请输入描述', 'warning')
        return
      }

      if (!this.formData.pcurl.trim()) {
        this.showToast('请输入链接', 'warning')
        return
      }

      if (!this.imageUrl) {
        this.showToast('请上传图片', 'warning')
        return
      }

      try {
        // 如果有新选择的图片，先上传
        let imageUrl = this.imageUrl
        if (this.tempImageFile) {
          const uploadedUrl = await this.uploadImage()
          if (!uploadedUrl) return // 上传失败则终止
          imageUrl = uploadedUrl
        }

        let res;
        if (this.isEdit) {
          // 修改操作
          res = await apiClient.post(
              '/patient/changeHotArticles',
              {
                id: this.currentItem.id,
                name: this.formData.name,
                description: this.formData.description,
                pcurl: this.formData.pcurl,
                picture: imageUrl
              }
          );
        } else {
          // 新增操作
          res = await apiClient.post(
              '/patient/addHotArticles',
              {
                name: this.formData.name,
                description: this.formData.description,
                pcurl: this.formData.pcurl,
                picture: imageUrl,
                authority: localStorage.getItem('authority') || '',
                isused: '启用'
              }
          );
        }

        if (res.data.code === 1) {
          this.showToast(this.isEdit ? '修改成功' : '添加成功', 'success')
          this.showDialog = false
          this.fetchArticlesData()
        } else {
          this.showToast(`${this.isEdit ? '修改' : '添加'}失败: ${res.data.msg || ''}`, 'error')
        }
      } catch (error) {
        console.error('提交数据出错:', error)
        this.showToast('操作失败，请重试', 'error')
      }
    },

    // 显示提示信息
    showToast(message, type = 'info') {
      alert(`${type}: ${message}`)
    }
  }
}
</script>

<style scoped>
.hot-articles-page {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.add-btn {
  padding: 6px 12px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #e0e0e0;
}

/* 统一表格行高和垂直对齐，确保按钮与其他列内容平行 */
.data-table th,
.data-table td {
  padding: 8px 15px; /* 减少内边距，匹配按钮尺寸 */
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
  word-break: break-all;
  vertical-align: middle; /* 核心：所有单元格内容垂直居中 */
}

/* 固定行高，避免按钮区域高低不一 */
.data-table tr {
  height: 70px;
}

.data-table th {
  background-color: #f5f5f5;
  font-weight: bold;
  font-size: 14px;
}

/* 图片尺寸调整，与行高匹配 */
.article-img {
  width: 100px;
  height: 60px; /* 图片高度从40px增加到60px，匹配行高 */
  object-fit: contain; /* 改为contain，确保图片完整显示（不裁剪） */
  /* object-fit: cover; 原样式可能裁剪图片，改为contain更适合完整显示需求 */
}

.link-cell {
  max-width: 200px;
  font-size: 14px;
}

/* 管理列样式简化，移除冗余容器 */
.action-cell {
  padding: 5px 15px;
}

/* 按钮样式统一为small尺寸，与药品页面保持一致 */
.status-btn, .edit-btn {
  padding: 5px 12px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  font-size: 12px; /* 统一小按钮字体 */
  line-height: 1;
  margin-right: 5px; /* 按钮间距 */
}

/* 状态按钮颜色标准化 */
.status-btn.success {
  background-color: #52c41a; /* Element success标准色 */
  color: white;
}

.status-btn.danger {
  background-color: #ff4d4f; /* Element danger标准色 */
  color: white;
}

.edit-btn.primary {
  background-color: #1890ff; /* Element primary标准色 */
  color: white;
}

.empty-tip {
  text-align: center;
  color: #999;
  padding: 40px;
}

/* 对话框样式优化，增加取消按钮 */
.dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-container {
  width: 90%;
  max-width: 600px;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.dialog-header {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.dialog-content {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

.form-item {
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
}

.form-item label {
  margin-bottom: 8px;
  font-weight: 500;
}

.form-item input,
.form-item textarea {
  padding: 8px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 14px;
}

.form-item textarea {
  min-height: 80px;
  resize: vertical;
}

.char-count {
  align-self: flex-end;
  margin-top: 4px;
  font-size: 12px;
  color: #999;
}

.image-upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 16px;
}

.image-preview, .image-placeholder {
  width: 200px;
  height: 200px;
  border: 1px dashed #e0e0e0;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 16px;
}

.preview-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.upload-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 16px;
}

.dialog-footer {
  padding: 16px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  justify-content: flex-end;
  gap: 10px; /* 按钮间距 */
}

/* 新增取消按钮，与提交按钮样式区分 */
.cancel-btn {
  padding: 8px 16px;
  background-color: #fff;
  color: #333;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
}

.submit-btn {
  padding: 8px 16px;
  background-color: #1890ff; /* 与其他页面提交按钮颜色统一 */
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>